package com.centit.airplaneinfo_db.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.centit.airplanebaseinfo.po.AirplaneBaseinfo;
import com.centit.airplaneinfo_db.dao.DbHbxxDao;
import com.centit.airplaneinfo_db.dao.DbOldInfoDjpqlDao;
import com.centit.airplaneinfo_db.dao.DbOldInfoGcwtlDao;
import com.centit.airplaneinfo_db.dao.DbRecordDao;
import com.centit.airplaneinfo_db.po.DbOldInfoDjpql;
import com.centit.airplaneinfo_db.po.DbOldInfoGcwtl;
import com.centit.airplaneinfo_db.po.DbRecord;
import com.centit.airplaneinfo_db.po.ExportExcelUtil;
import com.centit.airplaneinfo_db.service.DbRecordManager;
import com.centit.flowNode.po.FlowNode;
import com.centit.framework.common.JsonResultUtils;
import com.centit.framework.common.ResponseMapData;
import com.centit.framework.components.CodeRepositoryUtil;
import com.centit.framework.core.controller.BaseController;

import com.centit.framework.core.dao.CodeBook;
import com.centit.framework.model.basedata.IRoleInfo;
import com.centit.framework.model.basedata.IUnitInfo;
import com.centit.framework.model.basedata.IUserInfo;
import com.centit.framework.security.model.CentitUserDetails;
import com.centit.ideaInfo.po.IdeaInfo;
import com.centit.importData.dao.ShhzfjfdjDao;
import com.centit.support.algorithm.UuidOpt;
import com.centit.support.database.utils.PageDesc;
import com.centit.util.LayuiResultUtil;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.text.SimpleDateFormat;
import java.util.*;

@Controller
@RequestMapping("/dbRecord")
public class DbRecordController extends BaseController {

    @Resource
    private DbRecordManager dbRecordManager;

    @Resource
    public DbRecordDao dbRecordDao;

    @Resource
    public DbOldInfoGcwtlDao dbOldInfoGcwtlDao;

    @Resource
    public DbHbxxDao dbHbxxDao;

    @Resource
    public DbOldInfoDjpqlDao dbOldInfoDjpqlDao;

    /**
     * 查询列表数据
     * @param field
     * @param pageDesc
     * @param request
     * @param response
     */
    @RequestMapping(method = RequestMethod.GET)
    public void list(String[] field, PageDesc pageDesc, HttpServletRequest request, HttpServletResponse response) {

        //获取查询参数
        Map<String, Object> searchColumn = collectRequestParameters(request);
        searchColumn.put("dataState","1");
        //获取分页参数
        String limit = request.getParameter("limit");// 必要写法
        if (org.apache.commons.lang3.StringUtils.isBlank(limit)) {
            limit = "20";
        }
        pageDesc.setPageSize(Integer.parseInt(limit));// 设置参数


        System.out.println("---searchColumn----"+ JSON.toJSONString(searchColumn));
        //每个人都能查看所有的数据
        JSONArray jsonArrayObjects = dbRecordManager.listObjectsAsJson(searchColumn, pageDesc);

        ResponseMapData resData = new ResponseMapData();
        resData.addResponseData(OBJLIST, jsonArrayObjects);
        resData.addResponseData(PAGE_DESC, pageDesc);

        LayuiResultUtil.layuiwriteResponseDataAsJson(resData, pageDesc, response);
    }

    /**
     * 上传收费统计表
     * @param file
     * @param response
     * @param request
     */
    @RequestMapping(value = "/uploadSftjb", method = { RequestMethod.POST })
    //@ResponseBody
    //@MyDictionary
    public void uploadSftjb(
            @RequestParam(value = "file", required = false) MultipartFile file,
            HttpServletResponse response, HttpServletRequest request) {
        CentitUserDetails cud = getLoginUser(request);
        try {
            String type = file.getOriginalFilename();
            System.out.println("--------type--------"+ type);
            System.out.println("--------loginUser--------"+ cud.getUserCode());
            StringBuilder fileTitle=new StringBuilder();
            fileTitle.append(UuidOpt.getUuidAsString32()).append(type);
            System.out.println("--------fileTitle--------"+ fileTitle.toString());
            saveToLocal(file,type,request,fileTitle.toString());
            /*导入方法首先校验模板是否对应*/
            ExportExcelUtil exportExcelUtil=new ExportExcelUtil();
            exportExcelUtil.initDao(dbRecordDao,dbOldInfoGcwtlDao,dbHbxxDao,dbOldInfoDjpqlDao);
            ExportExcelUtil.RESULT_STR_LIST_All_POOL.put(cud.getUserCode(),new ArrayList<>());
            String str=exportExcelUtil.importExcel(file,cud.getUserCode(),type);

            Map<String,Object> resultMap=new HashMap<>();
            resultMap.put("wrong.url","");
            resultMap.put("wrong.data","");
            JsonResultUtils.writeSingleDataJson(resultMap, response);

        }catch (Exception e){
            e.printStackTrace();
            JsonResultUtils.writeErrorMessageJson(601, "操作失败,请联系系统管理员", response);
        }

    }
    /**
     * 上传航班信息表
     * @param file
     * @param response
     * @param request
     */
    @RequestMapping(value = "/uploadHbxx", method = { RequestMethod.POST })
    //@ResponseBody
    //@MyDictionary
    public void uploadHbxx(
            @RequestParam(value = "file", required = false) MultipartFile file,
            HttpServletResponse response, HttpServletRequest request) {
        CentitUserDetails cud = getLoginUser(request);
        String recId=request.getParameter("recId");
        //System.out.println("----recId----recId----recId----"+ recId);
        try {
            String type = file.getOriginalFilename();

            StringBuilder fileTitle=new StringBuilder();
            fileTitle.append(UuidOpt.getUuidAsString32()).append(type);
            saveToLocal(file,type,request,fileTitle.toString());

            ExportExcelUtil exportExcelUtil=new ExportExcelUtil();
            exportExcelUtil.initDao(dbRecordDao,dbOldInfoGcwtlDao,dbHbxxDao,dbOldInfoDjpqlDao);
            ExportExcelUtil.RESULT_STR_LIST_All_POOL.put(cud.getUserCode(),new ArrayList<>());
            String str=exportExcelUtil.importExcelHbxx(file,cud.getUserCode(),type,recId);

            Map<String,Object> resultMap=new HashMap<>();
            resultMap.put("wrong.url","");
            resultMap.put("wrong.data","");
            JsonResultUtils.writeSingleDataJson(resultMap, response);

        }catch (Exception e){
            e.printStackTrace();
            JsonResultUtils.writeErrorMessageJson(601, "操作失败,请联系系统管理员", response);
        }

    }

    /**
     * 上传收费统计表(定检)
     * @param file
     * @param response
     * @param request
     */
    @RequestMapping(value = "/uploadSftjbDjpq", method = { RequestMethod.POST })
    //@ResponseBody
    //@MyDictionary
    public void uploadSftjbDjpq(
            @RequestParam(value = "file", required = false) MultipartFile file,
            HttpServletResponse response, HttpServletRequest request) {
        CentitUserDetails cud = getLoginUser(request);
        try {
            String type = file.getOriginalFilename();
            StringBuilder fileTitle=new StringBuilder();
            fileTitle.append("djpq").append(UuidOpt.getUuidAsString32()).append(type);
            System.out.println("--------fileTitle--------"+ fileTitle.toString());
            saveToLocal(file,type,request,fileTitle.toString());
            /*导入方法首先校验模板是否对应*/
            ExportExcelUtil exportExcelUtil=new ExportExcelUtil();
            exportExcelUtil.initDao(dbRecordDao,dbOldInfoGcwtlDao,dbHbxxDao,dbOldInfoDjpqlDao);
            ExportExcelUtil.RESULT_STR_LIST_All_POOL.put(cud.getUserCode(),new ArrayList<>());
            String str=exportExcelUtil.importExcelDjpq(file,cud.getUserCode(),type);

            Map<String,Object> resultMap=new HashMap<>();
            resultMap.put("wrong.url","");
            resultMap.put("wrong.data","");
            JsonResultUtils.writeSingleDataJson(resultMap, response);

        }catch (Exception e){
            e.printStackTrace();
            JsonResultUtils.writeErrorMessageJson(601, "操作失败,请联系系统管理员", response);
        }

    }

    /**
     * 上传机队年度计划表
     * @param file
     * @param response
     * @param request
     */
    @RequestMapping(value = "/uploadJdndjh", method = { RequestMethod.POST })
    //@ResponseBody
    //@MyDictionary
    public void uploadJdndjh(
            @RequestParam(value = "file", required = false) MultipartFile file,
            HttpServletResponse response, HttpServletRequest request) {
        CentitUserDetails cud = getLoginUser(request);
        String recId=request.getParameter("recId");

        try {
            String type = file.getOriginalFilename();

            StringBuilder fileTitle=new StringBuilder();
            fileTitle.append("djpq").append(UuidOpt.getUuidAsString32()).append(type);
            saveToLocal(file,type,request,fileTitle.toString());

            ExportExcelUtil exportExcelUtil=new ExportExcelUtil();
            exportExcelUtil.initDao(dbRecordDao,dbOldInfoGcwtlDao,dbHbxxDao,dbOldInfoDjpqlDao);
            ExportExcelUtil.RESULT_STR_LIST_All_POOL.put(cud.getUserCode(),new ArrayList<>());
            String str=exportExcelUtil.importExcelJdndjh(file,cud.getUserCode(),type,recId);

            Map<String,Object> resultMap=new HashMap<>();
            resultMap.put("wrong.url","");
            resultMap.put("wrong.data","");
            JsonResultUtils.writeSingleDataJson(resultMap, response);

        }catch (Exception e){
            e.printStackTrace();
            JsonResultUtils.writeErrorMessageJson(601, "操作失败,请联系系统管理员", response);
        }

    }


    public void saveToLocal(MultipartFile file,String type,HttpServletRequest request,String title){
        try {
            String outFilePath = request.getSession().getServletContext().getRealPath("/")
                    + "Document" + File.separator + title;

            System.out.println("-----outFilePath------"+outFilePath);
            System.out.println("-----uploaderpath------"+ CodeRepositoryUtil.getSysConfigValue("uploaderpath"));
            File outFile = new File(outFilePath);
            FileOutputStream fos=null;
            try {
                fos = new FileOutputStream(outFile);
                if(type.endsWith(".xls")){
                    Workbook workbook= new HSSFWorkbook(file.getInputStream());
                    workbook.write(fos);
                }else {
                    XSSFWorkbook workbook= new XSSFWorkbook(file.getInputStream());
                    workbook.write(fos);
                }
                fos.flush();
            } catch (FileNotFoundException e1) {
                e1.printStackTrace();
                System.out.println("---文件没找到---");
            }


        }catch (Exception e){
            e.printStackTrace();
        }


    }


    @RequestMapping(value = "/{recId}/{type}", method = { RequestMethod.GET })
    public ModelAndView toDbPage(@PathVariable String recId, @PathVariable String type,
                                  HttpServletResponse response, HttpServletRequest request) {
        ModelAndView mv = new ModelAndView();
        CentitUserDetails cud = getLoginUser(request);

        String forward = "forward:/modules/airplaneinfo_db/gcwt_contrast.jsp";


        if(StringUtils.isNotEmpty(recId)){
            if ("gcwt".equals(type)) {
                forward =  "forward:/modules/airplaneinfo_db/gcwt_contrast.jsp";

                Map<String,Object> filterMap=new HashMap<>();
                filterMap.put("recordId",recId);
                filterMap.put("tableType","2");
                filterMap.put("dataTypeIn",new String[]{"1","2"});
                filterMap.put(CodeBook.SELF_ORDER_BY, " ORDER_NUM ");
                List<DbOldInfoGcwtl> dbOldInfoA=dbOldInfoGcwtlDao.listObjects(filterMap);

                filterMap.put("dataTypeIn",new String[]{"3"});
                List<DbOldInfoGcwtl> dbNewInfoList=dbOldInfoGcwtlDao.listObjects(filterMap);
                JSONArray dbNewInfoA=new JSONArray();
                if(dbNewInfoList.size()>0){
                    for(DbOldInfoGcwtl w:dbNewInfoList){
                        if("all".equals(w.getAirPlaneType())){
                            w.setDataType("2");
                            dbNewInfoA.add(w);
                        }else {
                            dbNewInfoA.add(w);
                        }
                    }
                }else {
                    dbNewInfoA=dbRecordManager.newDbRecordValue(dbOldInfoA,recId);

                }



                Map<String,Object> filterMapZzj=new HashMap<>();
                filterMapZzj.put("recordId",recId);
                filterMapZzj.put("tableType","3");
                filterMapZzj.put("dataTypeIn",new String[]{"1","2"});
                filterMapZzj.put(CodeBook.SELF_ORDER_BY, " ORDER_NUM ");
                List<DbOldInfoGcwtl> dbOldInfoZzj=dbOldInfoGcwtlDao.listObjects(filterMapZzj);
                filterMapZzj.put("dataTypeIn",new String[]{"3"});
                List<DbOldInfoGcwtl> dbNewInfoZzjList=dbOldInfoGcwtlDao.listObjects(filterMapZzj);
                JSONArray dbNewInfoZzj=new JSONArray();
                if(dbNewInfoZzjList.size()>0){
                    for(DbOldInfoGcwtl w:dbNewInfoZzjList){
                        if("all".equals(w.getAirPlaneType())){
                            w.setDataType("2");
                            dbNewInfoZzj.add(w);
                        }else {
                            dbNewInfoZzj.add(w);
                        }
                    }
                }else {
                    dbNewInfoZzj=dbRecordManager.newDbRecordValue(dbOldInfoZzj,recId);

                }
                //JSONArray dbNewInfoZzj=dbRecordManager.newDbRecordValue(dbOldInfoA,recId);
                //System.out.println("----dbNewInfoZzj--dbNewInfoZzj----"+JSON.toJSONString(dbNewInfoZzj));

                mv.addObject("recId", recId);
                mv.addObject("dbOldInfoA", dbOldInfoA);
                mv.addObject("dbNewInfoA", dbNewInfoA);
                mv.addObject("dbOldInfoZzj", dbOldInfoZzj);
                mv.addObject("dbNewInfoZzj", dbNewInfoZzj);
            }else if("djpq".equals(type)){
                forward = "forward:/modules/airplaneinfo_db/djpq_contrast.jsp";

                Map<String,Object> filterMap=new HashMap<>();
                filterMap.put("recordId",recId);
                filterMap.put("dataType","1");
                //filterMap.put(CodeBook.SELF_ORDER_BY, " ORDER_NUM ");
                List<DbOldInfoDjpql> dbOldInfoDjpq=dbOldInfoDjpqlDao.listObjects(filterMap);

                filterMap.put("dataType","2");
                List<DbOldInfoDjpql> dbNewInfoDjpq=dbOldInfoDjpqlDao.listObjects(filterMap);
                Map<String, Object> resultMap=dbRecordManager.contrastData(dbOldInfoDjpq,dbNewInfoDjpq);
                mv.addObject("recId", recId);
                mv.addObject("dbOldInfoDjpq", resultMap.get("old"));
                mv.addObject("dbNewInfoDjpq",  resultMap.get("new"));

            }else if("edit".equals(type)){
                forward = "forward:/modules/airplaneinfo_db/dbRecordInfo.jsp";
                DbRecord dbRecord=dbRecordManager.getObjectById(recId);
                mv.addObject("dbRecord", dbRecord);
            }

        }


        mv.addObject(OBJECT, new ArrayList<>());

        mv.setViewName(forward);
        return mv;
    }

    @RequestMapping(value = "/{recId}", method = {RequestMethod.PUT})
    public void updateDbRecord(@PathVariable String recId,
                                       @Valid DbRecord dbRecord, HttpServletResponse response, HttpServletRequest request) {
        CentitUserDetails cud = getLoginUser(request);
        DbRecord dbRecord1=dbRecordManager.getObjectById(recId);
        if(dbRecord1!=null){
            dbRecord1.copyNotNullProperty(dbRecord);
            dbRecordManager.updateObject(dbRecord1);
        }

        JsonResultUtils.writeSingleDataJson("操作成功",response);
    }

    /**
     * 删除单个  飞机基础信息

     * @param recId  REC_ID
     */
    @RequestMapping(value = "/{recId}", method = {RequestMethod.DELETE})
    public void deleteAirplaneBaseinfo(@PathVariable String recId, HttpServletResponse response, HttpServletRequest request) {

        DbRecord dbRecord1=dbRecordManager.getObjectById(recId);
        if(dbRecord1!=null){
            dbRecord1.setDataState("0");
            dbRecordManager.updateObject(dbRecord1);
        }
        JsonResultUtils.writeSingleDataJson("操作成功",response);
    }


    @RequestMapping(value = "/editHbxx", method = {RequestMethod.POST})
    public void editHbxx(@RequestBody List<DbOldInfoGcwtl> dbOldInfoGcwtls, HttpServletResponse response, HttpServletRequest request) {

        System.out.println("---dbOldInfoGcwtls--------"+JSON.toJSONString(dbOldInfoGcwtls));
        Map<String,Object> filterMap=new HashMap<>();
        filterMap.put("recordId",dbOldInfoGcwtls.get(0).getRecordId());
        filterMap.put("tableType",dbOldInfoGcwtls.get(0).getTableType());
        filterMap.put("dataType","3");
        List<DbOldInfoGcwtl> dbOldInfo=dbOldInfoGcwtlDao.listObjects(filterMap);
        for (DbOldInfoGcwtl delObj:dbOldInfo){
            delObj.setDataType("4");
            dbOldInfoGcwtlDao.mergeObject(delObj);
        }
        for (DbOldInfoGcwtl addObj:dbOldInfoGcwtls){
            addObj.setRecId(UuidOpt.getUuidAsString32());
            dbOldInfoGcwtlDao.saveNewObject(addObj);
        }

        JsonResultUtils.writeSingleDataJson("操作成功",response);

    }


    @RequestMapping(value = "/dbNewInfo/{recId}", method = { RequestMethod.GET })
    public void dbNewInfo(@PathVariable String recId, HttpServletResponse response) {
        try {

            Map<String,Object> filterMap=new HashMap<>();
            filterMap.put("recordId",recId);
            filterMap.put("tableType","2");
            filterMap.put("dataTypeIn",new String[]{"1","2"});
            filterMap.put(CodeBook.SELF_ORDER_BY, " ORDER_NUM ");
            List<DbOldInfoGcwtl> dbOldInfoA=dbOldInfoGcwtlDao.listObjects(filterMap);

            filterMap.put("dataTypeIn",new String[]{"3"});
            List<DbOldInfoGcwtl> dbNewInfoList=dbOldInfoGcwtlDao.listObjects(filterMap);
            JSONArray dbNewInfoA=new JSONArray();
            if(dbNewInfoList.size()>0){
                for(DbOldInfoGcwtl w:dbNewInfoList){
                    if("all".equals(w.getAirPlaneType())){
                        w.setDataType("2");
                        dbNewInfoA.add(w);
                    }else {
                        dbNewInfoA.add(w);
                    }
                }
            }else {
                dbNewInfoA=dbRecordManager.newDbRecordValue(dbOldInfoA,recId);

            }



            Map<String,Object> filterMapZzj=new HashMap<>();
            filterMapZzj.put("recordId",recId);
            filterMapZzj.put("tableType","3");
            filterMapZzj.put("dataTypeIn",new String[]{"1","2"});
            filterMapZzj.put(CodeBook.SELF_ORDER_BY, " ORDER_NUM ");
            List<DbOldInfoGcwtl> dbOldInfoZzj=dbOldInfoGcwtlDao.listObjects(filterMapZzj);

            filterMapZzj.put("dataTypeIn",new String[]{"3"});
            List<DbOldInfoGcwtl> dbNewInfoZzjList=dbOldInfoGcwtlDao.listObjects(filterMapZzj);
            JSONArray dbNewInfoZzj=new JSONArray();
            if(dbNewInfoZzjList.size()>0){
                for(DbOldInfoGcwtl w:dbNewInfoZzjList){
                    if("all".equals(w.getAirPlaneType())){
                        w.setDataType("2");
                        dbNewInfoZzj.add(w);
                    }else {
                        dbNewInfoZzj.add(w);
                    }
                }
            }else {
                dbNewInfoZzj=dbRecordManager.newDbRecordValue(dbOldInfoZzj,recId);

            }


            Map<String,Object> resultMap=new HashMap<>();
            resultMap.put("recId",recId);
            resultMap.put("dbOldInfoA",dbOldInfoA);
            resultMap.put("dbNewInfoA",dbNewInfoA);
            resultMap.put("dbOldInfoZzj",dbOldInfoZzj);
            resultMap.put("dbNewInfoZzj",dbNewInfoZzj);
            JsonResultUtils.writeSingleDataJson(resultMap, response);

        }catch (Exception e){
            e.printStackTrace();
            JsonResultUtils.writeErrorMessageJson(601, "操作失败,请联系系统管理员", response);
        }


    }


    @RequestMapping(value = "/revertHbxx/{recId}", method = { RequestMethod.GET })
    public void revertHbxx(@PathVariable String recId,HttpServletRequest request, HttpServletResponse response) {
        try {
            String tableType=request.getParameter("tableType");
            Map<String,Object> filterMap=new HashMap<>();
            filterMap.put("recordId",recId);
            filterMap.put("tableType",tableType);
            filterMap.put("dataType","3");
            System.out.println("-----filterMap------"+JSON.toJSONString(filterMap));
            List<DbOldInfoGcwtl> dbOldInfo=dbOldInfoGcwtlDao.listObjects(filterMap);
            for (DbOldInfoGcwtl delObj:dbOldInfo){
                delObj.setDataType("4");
                dbOldInfoGcwtlDao.mergeObject(delObj);
            }

            JsonResultUtils.writeSingleDataJson("操作成功",response);

        }catch (Exception e){
            e.printStackTrace();
            JsonResultUtils.writeErrorMessageJson(601, "操作失败,请联系系统管理员", response);
        }


    }


}
